//
//  TLAleartViewButton.swift
//  TAleartView
//
//  Created by 唐基林 on 2025/1/22.
//

import UIKit

class TLAleartViewButton: UIView {
    
    var dismissHandler: (() -> Void)?
    
    var okButtonClickHandler: ((String) -> Void)?
    /// 标题
    var titel: String
    
    /// 确定按钮
    var okbtnName: String
    
    var dataArray:[ String]
    
    init(frame: CGRect, titel:String = "选择器",okbtnName:String = "确定",centent:Array<String> = []) {
        self.titel = titel
        self.dataArray = centent
        self.okbtnName = okbtnName
        super.init(frame: frame)
        self.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        
        self.setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var menView:UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 15
        return view
    }()
    
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.layer.cornerRadius = 15
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .singleLine
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)
        tableView.register(TLAleartViewButtonCell.self, forCellReuseIdentifier: TLAleartViewButtonCell.identifier)
        return tableView
    }()
    
    lazy var titelab:UILabel = {
        let lab = UILabel(frame: .zero)
        lab.text = self.titel
        lab.textAlignment = .center
        lab.font = .boldSystemFont(ofSize: 14)
        lab.textColor = .gray
        return lab
    }()
    
    lazy var okbutton:UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle(self.okbtnName, for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14)
        btn.addTarget(self, action: #selector(okbuttonClick), for: .touchUpInside)
        return btn
    }()
}

extension TLAleartViewButton
{
    @objc func okbuttonClick() {
        if (self.dismissHandler != nil) {
            dismissHandler?()
        }
        self.removeView()
    }
    
    private func removeView() {
        UIView.animate(withDuration: 0.3) {
            self.alpha = 0.0
        } completion: { _ in
            self.removeFromSuperview()
        }
    }
}

extension TLAleartViewButton:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(
            withIdentifier:TLAleartViewButtonCell.identifier,
            for: indexPath
        ) as? TLAleartViewButtonCell else {
            return UITableViewCell()
        }
        
        cell.selectionStyle = .none
        
        cell.configure(with: self.dataArray[indexPath.row])
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        TLog("选中了第 \(indexPath.row) 行")
        if self.okButtonClickHandler != nil {
            self.okButtonClickHandler!(self.dataArray[indexPath.row])
        }
        self.removeView()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
}

extension TLAleartViewButton {
    private func setUI() {
        let buttonInset = safeAreaInsets.bottom
        TLog("array count: \(self.dataArray.count) buttonInset\(buttonInset)")
        self.addSubview(self.menView)
        self.menView.frame.origin.y = self.bounds.height // 让 menView 从屏幕底部外部开始
        self.menView.addSubview(self.tableView)
        self.menView.addSubview(self.titelab)
        self.menView.addSubview(self.okbutton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let bottomInset = getSafeAreaInsets().bottom
        TLog("底部安全区域: \(bottomInset)")
        self.menView.snp.makeConstraints { make in
            make.left.equalTo(self).offset(15)
            make.right.equalTo(self).offset(-15)
            make.bottom.equalTo(self).offset(-bottomInset)
            make.height.equalTo(90 + self.dataArray.count * 60)
        }
        
        self.titelab.snp.makeConstraints { make in
            make.left.right.equalTo(self.menView)
            make.top.equalTo(self.menView).offset(15)
            make.height.equalTo(15)
        }
        
        self.tableView.snp.makeConstraints { make in
            make.left.right.equalTo(self.menView)
            make.top.equalTo(self.menView).offset(55)
            make.bottom.equalTo(self.menView).offset(-60)
        }
        
        self.okbutton.snp.makeConstraints { make in
            make.left.bottom.right.equalTo(self.menView)
            make.top.equalTo(self.tableView.snp_bottomMargin)
        }
    }
    
    public func showWithAnimation() {
        // Animate menView slides up
        UIView.animate(withDuration: 0.3,
                       delay: 0,
                       options: [.curveEaseInOut],
                       animations: {
            // 通过设置 menView 的性状到位置
            self.menView.frame.origin.y = self.bounds.height - self.menView.frame.height
        }, completion: nil)
    }
}
